<template>
    <el-form ref="formRef" :model="formParams" :rules="rules" label-width="110px" :disabled="false">
        <aside class="form-title">基础信息设置</aside>
        <el-form-item label="活动名称" prop="activity_name">
            <el-input
                v-model.trim="formParams.activity_name"
                maxlength="20"
                show-word-limit
                placeholder="请输入活动名称" />
        </el-form-item>
        <el-form-item label="所属分组" prop="group_id">
            <el-cascader
                ref="cascaderRef"
                v-model="formParams.group_id"
                :props="defaultProps"
                :options="groupOptions"
                @change="orgChange" />
        </el-form-item>
        <el-form-item
            label="活动有效期"
            prop="period_type"
            class="form-radio-item"
            :class="{ 'activity-time': formParams.period_type === 2 }">
            <el-radio-group v-model="formParams.period_type" prop="period_type" @change="handlePeriodTypeChange">
                <el-radio :label="1">永久</el-radio>
                <el-radio :label="2">自定义期限</el-radio>
            </el-radio-group>
            <el-form-item v-if="formParams.period_type === 2">
                <div v-if="formDisabled" class="edit-activity-time">
                    <el-date-picker
                        v-model="formParams.activity_time[0]"
                        disabled
                        type="datetime"
                        format="YYYY-MM-DD HH:mm:ss"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        placeholder="开始时间" />
                    <el-date-picker
                        v-model="formParams.activity_time[1]"
                        prefix-icon="none"
                        type="datetime"
                        format="YYYY-MM-DD HH:mm:ss"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        placeholder="结束时间"
                        :disabled-date="disabledDate"
                        :default-time="new Date(2000, 1, 1, 23, 59, 59)"
                        @change="checkActivityTime" />
                </div>
                <el-date-picker
                    v-else
                    v-model="formParams.activity_time"
                    type="datetimerange"
                    :disabled-date="disabledDate"
                    :default-time="defaultTime()"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    range-separator="-"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    @change="checkActivityTime" />
            </el-form-item>
        </el-form-item>
        <el-form-item label="活动说明" prop="description">
            <el-input
                v-model="formParams.description"
                type="textarea"
                maxlength="500"
                :rows="5"
                show-word-limit
                placeholder="请输入活动说明" />
        </el-form-item>
        <el-form-item label="活动信息" prop="activity_info_switch" class="form-radio-item">
            <el-switch
                v-model="formParams.activity_info_switch"
                :active-value="2"
                :inactive-value="1"
                @change="handleChangeActivityTabs" />
            <span class="form-tip"> 开启后，助力好友页面会展示活动信息 </span>
            <div v-show="isOpen(formParams.activity_info_switch)" class="form-tinymce-editor">
                <tinymce-editor v-model="formParams.activity_info_content" :config="editorConfig" />
            </div>
        </el-form-item>
        <aside class="form-title">引流成员</aside>
        <el-form-item label="添加好友规则" prop="add_friends_switch" class="form-radio-item">
            <div class="form-switch-tip">
                <el-switch v-model="formParams.add_friends_switch" :active-value="2" :inactive-value="1" />
                <span class="form-tip">
                    开启后，只要添加过企业任意一个员工企业微信就可以参与；不开启，则至少要添加1位引流员工的企业微信
                </span>
            </div>
        </el-form-item>
        <el-form-item label="引流员工" prop="user_list">
            <el-button type="primary" plain @click="openUserDialog">
                <el-icon><Plus /></el-icon>
                <span>添加员工</span>
            </el-button>
            <render-user-tags v-model:tags="formParams.user_list" />
        </el-form-item>
        <el-form-item label="助力者员工分配" prop="helper_staff_divide" class="form-radio-item helper-staff-divide">
            <el-radio-group v-model="formParams.helper_staff_divide">
                <el-radio :label="1">
                    <span>随机分配</span>
                    <span class="form-tip"> 助力者添加的企业成员，为引流员工中的随机一位 </span>
                </el-radio>
                <el-radio :label="2">
                    <span>溯源员工</span>
                    <span class="form-tip">
                        助力者添加的企业成员，为分享客户所添加的引流员工（若分享客户的企微好友不在引流员工里，将随机分配）：如，客户A添加员工甲，分享给客户B后，客户B添加的也是员工甲，以此类推
                    </span>
                </el-radio>
            </el-radio-group>
        </el-form-item>
    </el-form>
    <ZW-depart ref="departRef" :limit-num="100" @submit="addDepartToUserList" />
</template>
<script lang="ts" setup>
import { reactive, ref, onBeforeMount, inject } from 'vue';
import { useRoute } from 'vue-router';
import { ElMessage, FormInstance, FormRules } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';

import ZWDepart from '@/components/ZWDepart1.0.vue';
import TinymceEditor from '@/components/TinymceEditor.vue';

import renderUserTags from '@/components/zw/activity/render-tags/render-user-tags.vue';

import { uploadFile2 } from '@/api/common';
import { getGroupList } from '@/api/concreation';
import { defaultTime } from '@/utils/utils';

import { isOpen } from '../utils';
import { IPageType } from '../utils/interface';
// 表单字段
import { formParams } from '../utils/paramsManager';

const pageType: IPageType | undefined = inject('pageType');
const route = useRoute();
const emit = defineEmits(['changePhoneTabs']);

/** 进行中、结束的情况下禁用 */
const formDisabled: any = inject('formDisabled');
/* ----------------------------表单内容-start---------------------------- */
const formRef = ref<FormInstance>();
const cascaderRef: any = ref(null); // 选择分组ref

const disabledDate = (data: any) => {
    // 编辑状态下禁用活动创建之前
    if (formDisabled?.value && formParams.created_at) {
        return +data < +new Date(formParams.created_at) - 86400000;
    }
    // 86400000 => 一天的时间毫秒
    return +data < +new Date() - 86400000;
};
// 校验活动名称
const checkActivityName = (ruls: any, value: any, callback: any) => {
    if (!value) {
        return callback(new Error('请输入活动名称'));
    }

    if (value.length > 20) {
        return callback(new Error('请输入20个文字以内的活动名称'));
    }

    callback();
};
// 校验活动时间
const checkPeriodType = (ruls: any, value: any, callback: any) => {
    if (!value) {
        return callback(new Error('请选择活动有效期类型'));
    }

    if (value === 2) {
        const result = formParams.activity_time?.every((item: any) => item);
        if (!result || formParams.activity_time?.length < 2) return callback(new Error('请选择活动有效期'));

        // 校验结束时间和开始时间
        const [startTime, endTime] = formParams.activity_time;
        if (+new Date(startTime) >= +new Date(endTime)) {
            return callback(new Error('活动结束时间不能小于活动开始时间'));
        }
    }
    callback();
};
// 校验员工列表
const checkUserList = (ruls: any, value: any, callback: any) => {
    if (!value || !value.length) {
        return callback(new Error('请添加引流员工'));
    }
    callback();
};

// 校验活动分组
const checkGroupId = (ruls: any, value: any, callback: any) => {
    if (value || value === 0) {
        return callback();
    }
    return callback(new Error('请选择活动分组'));
};

const rules = reactive<FormRules>({
    activity_name: [{ required: true, validator: checkActivityName, trigger: 'change' }],
    period_type: [{ required: true, validator: checkPeriodType, trigger: 'blur' }],
    group_id: [{ required: true, validator: checkGroupId, trigger: 'change' }],
    user_list: [{ required: true, validator: checkUserList, trigger: 'change' }]
});

/**
 * 校验基本信息表单
 */
const validate = async () => {
    return await formRef.value?.validate();
};

/**
 * 活动结束时间变更时校验开始和结束时间
 */
const checkActivityTime = () => {
    formRef.value?.validateField(['period_type']);
};
/* ----------------------------表单内容-end---------------------------- */

/* ----------------------------分组-start---------------------------- */
const groupOptions = reactive<Array<any>>([]);
const defaultProps = {
    checkStrictly: true, // 是否严格的遵守父子节点不互相关联
    emitPath: false,
    multiple: false,
    label: 'name',
    value: 'id'
};
// 获取活动分组
const onGroupgList = async () => {
    const res: any = await getGroupList({ type: 30, name: '' });
    groupOptions.push(...res.data);

    formParams.group_id = Number(route.query?.group_id) || 0;
};

onBeforeMount(() => {
    onGroupgList();
});
/* ----------------------------分组-end---------------------------- */

/* ----------------------------选择员工-start---------------------------- */
const departRef = ref<any>();
const openUserDialog = () => {
    departRef.value.appDialog.visible = true;
    departRef.value.selectedMember = [...formParams.user_list];
};
const addDepartToUserList = (data: Array<{ id: number; name: string }>) => {
    formParams.user_list.length = 0;
    formParams.user_list.push(...data);
    formRef.value?.clearValidate(['user_list']);
};
/* ----------------------------选择员工-end---------------------------- */

/* ----------------------------富文本-start---------------------------- */
/**
 * 富文本配置覆盖，主要覆盖文件上传
 * @property {Function} images_upload_handler 自定义上传图片，把图片的处理成后端的url
 * @property {Function} file_picker_callback 自定义上传文件，把媒体文件的处理成后端的url
 */
const editorConfig = {
    font_formats: 'Arial=arial,helvetica,sans-serif; 宋体=SimSun;  微软雅黑=Microsoft Yahei;', // 字体
    images_upload_handler: async (blobInfo: any, success: (url: string) => void, failure: (err: unknown) => void) => {
        const file = blobInfo.blob();
        try {
            const res = await uploadFile2({
                file: file,
                fileName: file.name
            });
            success(res.url);
        } catch (err) {
            failure(err);
        }
    },
    // 文件上传音频，视频、图片等
    file_picker_callback: (callback: any, value: any, meta: any) => {
        // 只允许上传图片、音频、视频
        const metaFileTypeStrategy = {
            image: '.jpg, .jpeg, .png, .gif',
            media: '.wav, .mp3, .mp4, .mkv, .avi, .mov, .wmv',
            file: '.jpg, .jpeg, .png, .gif'
        };
        const filetype = metaFileTypeStrategy[meta.filetype ?? 'file'];
        const uploader: any = document.createElement('input'); //创建文件选择
        uploader.setAttribute('type', 'file');
        uploader.setAttribute('accept', filetype);
        uploader.click();
        uploader.onchange = async () => {
            const file = uploader.files[0]; //获取文件信息
            const fileName = file.name;
            // 校验文件类型
            if (!filetype.includes(fileName.split('.').pop().toLowerCase())) {
                ElMessage.warning('文件类型不支持');
                callback('');
                return;
            }

            const res: { url: string; code: string; name: string } = await uploadFile2({
                file,
                fileName
            });

            callback(res.url, {
                text: res.code,
                title: res.name
            });
        };
    }
};
/* ----------------------------富文本-end---------------------------- */

/* ----------------------------时间类-start---------------------------- */
// 切换类型时，根据编辑的情况设置默认的时间
const handlePeriodTypeChange = () => {
    formRef.value?.clearValidate(['period_type']);
    // 非编辑页面，不做设置默认值
    if (!pageType?.edit) {
        return;
    }
    if (formParams.period_type === 2 && !formParams.activity_time.length) {
        formParams.activity_time = [formParams.created_at];
    }
};
/* ----------------------------时间类型-end---------------------------- */
/** 改变外部样机tabs */
const handleChangeActivityTabs = () => {
    if (isOpen(formParams.activity_info_switch)) {
        emit('changePhoneTabs', 'activilyInfo');
        return;
    }

    // 关闭的情况下不传，样机会自动判断
    emit('changePhoneTabs');
};
// 选择完地区后立即关闭
const orgChange = () => {
    cascaderRef.value.togglePopperVisible();
};
defineExpose({
    validate,
    formParams
});
</script>
